//
//  DFVersion.m
//  dfutil
//
//  Created by Tom Booth on 25/06/2009.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "DFVersion.h"

// private functions
@interface DFVersion (PrivateMethods) 

@end

NSInteger compareCommands(id c1, id c2, void *context);




@implementation DFVersion

// synth propertys
@synthesize version;
@synthesize path;
@synthesize commands;



- (id)initFromDefinition :(NSString*)pathToDefinition {
	self = [super init];
	
	NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	
	// init the command holder
	commands = [[NSMutableArray alloc] init];
	
	// create an xml doc obj from the pulled string
	NSString *xml = [NSString stringWithContentsOfFile:pathToDefinition];
	NSXMLDocument *doc = [[NSXMLDocument alloc] initWithXMLString:xml options:NSXMLDocumentTidyXML error:NULL];
	
	// get the commands
	NSXMLElement *root = [doc rootElement];
	NSArray *xml_commands = [root nodesForXPath:@"//command" error:NULL];
	
	// parse the xml	
	int i=0;
	for(NSXMLElement *command in xml_commands) {		
		
		// work out whether this is a row commands
		BOOL is_row_command = [DFUtility boolifyString:[[[command nodesForXPath:
													 [NSString stringWithFormat:@"%@%@",[command XPath],@"//createsrows"]
																	 error:NULL] objectAtIndex:0] stringValue]];
		if (is_row_command) {
			fprintf(stdout,"r");
			[commands addObject:[[DFRowCommand alloc] initWithXML:command]];
		}
		else {
			fprintf(stdout,"s");
			[commands addObject:[[DFSimpleCommand alloc] initWithXML:command]];
		}
		
		i++;
	}
	
	// finish and sort
	fprintf(stdout,"Sorting...");
	[commands sortUsingFunction:compareCommands context:nil];
	fprintf(stdout,"Done.\n");
	
	[pool drain];
	
	return self;
}

-(void) printCommands {
	
	for (DFCommand *c in commands) {
		NSLog(c.name);
	}
	
}




NSInteger compareCommands(id c1, id c2, void *context) {
	return [[c1 name] compare:[c2 name]];
}


@end
